package com.tty.utils;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.*;
import java.util.Random;

/**
 * @author ouyang
 * @create 2022-11-19-21:11
 */
//@Component
public class Util {

    private static String port;

    @Value("${server.port}")
    public void setPort(String port){
        Util.port = port;
    }

    public static boolean urlExist(String originalUrl) throws IOException {

        URL url = new URL(originalUrl);

        HttpURLConnection Connection = (HttpURLConnection) url.openConnection();

        int code = Connection.getResponseCode();

        return HttpURLConnection.HTTP_OK == code;

    }


    public static String transition() throws UnknownHostException {

        String code = Util.code();

        String host = InetAddress.getLocalHost().getHostAddress();


        String shortenUrl ="http://" + host + ":" + port + "/short/" + code;

        return shortenUrl;

    }

    public static String code(){

        Random random = new Random();
        StringBuilder sb = new StringBuilder();

        String bank = "1234567890abcdefghijklmnopqrstuvwxwzABCDEFGHIJKLMNOPORSTUVWXYZ";

        for (int i = 0; i < 6; i++) {
            char word = bank.charAt(random.nextInt(62));
            sb.append(word);
        }

        return sb.toString();
    }
}
